package com.sinacom.ibuilding.service;


import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;

import com.ibatis.dao.client.DaoManager;
import com.sinacom.ibuilding.beans.Contacts;
import com.sinacom.ibuilding.beans.Member;
import com.sinacom.ibuilding.beans.Role;
import com.sinacom.ibuilding.dao.DaoConfig;
import com.sinacom.ibuilding.dao.iface.MemberDao;
//import com.sinacom.ibuilding.util.Constants;
import com.sinacom.ibuilding.util.Constants;
import com.sinacom.ibuilding.util.PageModel;

public class MemberService {
	
	private MemberDao memberDao;
	private IdCreateService idService = new IdCreateService();
	public MemberService(){
		DaoManager	daoManager = DaoConfig.getDaoManager();
		memberDao = (MemberDao) daoManager.getDao(MemberDao.class);
	}
	public Member getMemberUsername(String username){
		if(StringUtils.isEmpty(username))return null;
	    Map map = new HashMap();
	    map.put("username", username);
	    List memberList = memberDao.getMemberList(map);
	    if(memberList != null && memberList.size()>0){
	        return (Member) memberList.get(0);
	    }
	    return null;
	}
	
	public Member getMemberSchoolCode(String schoolCode){
        if(StringUtils.isEmpty(schoolCode))return null;
        Map map = new HashMap();
        map.put("schoolCode", schoolCode);
        List memberList = memberDao.getMemberList(map);
        if(memberList != null && memberList.size()>0){
            return (Member) memberList.get(0);
        }
        return null;
    }
	
	public Member getMemberById(String id){
        if(StringUtils.isEmpty(id))return null;
        Map map = new HashMap();
        map.put("id", id);
        List memberList = memberDao.getMemberList(map);
        if(memberList != null && memberList.size()>0){
            return (Member) memberList.get(0);
        }
        return null;
    }
	
	public List getMemberList(){
		return memberDao.getMemberList(null);
	}
	
	public List getMemberByRole(String roleId){
		if(StringUtils.isEmpty(roleId))return null;
        Map map = new HashMap();
        map.put("searchRole", roleId);
		return memberDao.getMemberList(map);
	}
	
	public List getCatgoryMember(String category){
		Map map = new HashMap();
		map.put("category", category);
		return memberDao.getCatgoryMember(map);
	}
	
	public Member getMemberMobile(String mobile){
		if(StringUtils.isEmpty(mobile))return null;
        Map map = new HashMap();
        map.put("mobile", mobile);
        List memberList = memberDao.getMemberList(map);
        if(memberList != null && memberList.size()>0){
            return (Member) memberList.get(0);
        }
        return null;
    }
	
	public Member login(String loginName,String loginPwd){
		Member member = getMemberSchoolCode(loginName);
		if(member != null && DigestUtils.md5Hex(loginPwd).equals(member.getPassword())){
			return member;
		}else{
			member = getMemberMobile(loginName);
			if(member != null && DigestUtils.md5Hex(loginPwd).equals(member.getPassword())){
				return member;
			}
		}
		return null;
	}
	
	public Role getRoleById(String id){
		if(StringUtils.isEmpty(id))return null;
		Map map = new HashMap();
		map.put("id", id);
		List roleList = memberDao.getRole(map);
		if(roleList != null && roleList.size() > 0){
			Role role = (Role) roleList.get(0);
			return role;
		}
		return null;
	}
	
	public List getRoleByParent(String parentId){
		if(StringUtils.isEmpty(parentId))return null;
		Map map = new HashMap();
		map.put("parentId", parentId);
		List roleList = memberDao.getRole(map);
		return roleList;
	}
	
	public String getPathName(String memberId){
		if(StringUtils.isEmpty(memberId)) return null; 
		Map map = new HashMap();
		map.put("member", memberId); 
		List roleList = memberDao.getRole(map);
		if(roleList != null && roleList.size() > 0){
			Role role = (Role) roleList.get(0);
			if("0".equals(role.getParentId())){
				return role.getName();
			}else{
				Role role2 = getRoleById(role.getParentId());
				if("0".equals(role2.getParentId())){
					return role2.getName()+ " | "+role.getName();
				}else{
					Role role3 = getRoleById(role2.getParentId());
					return role3.getName()+ " | "+role2.getName()+ " | "+role.getName();
				}
			}
		}
		return null;
	}
	
	
	public Role getMemberRole(String memberId){
		if(StringUtils.isEmpty(memberId)) return null; 
		Map map = new HashMap();
		map.put("member", memberId); 
		List roleList = memberDao.getRole(map);
		Role memberRole = new Role();
		if(roleList != null && roleList.size() > 0){
			Set chargeSet = new HashSet();
			Set accessSet = new HashSet();
			for (int i = 0; i < roleList.size(); i++) {
				Role r = (Role) roleList.get(i);
				Role role = getRoledById(r.getId());
			//	role.setVisituser(new Integer(1));
				if(role != null){
					if(role.getUserMang()!=null && role.getUserMang().booleanValue()){
						memberRole.setUserMang(new Boolean(true));
					}
					if(role.getScheduleMang()!=null && role.getScheduleMang().booleanValue()){
						memberRole.setScheduleMang(new Boolean(true));
					}
					if(role.getNewsMang()!=null && role.getNewsMang().booleanValue()){
						memberRole.setNewsMang(new Boolean(true));
					}
					if(role.getMsgsend()!=null && role.getMsgsend().booleanValue()){
						memberRole.setMsgsend(new Boolean(true));
					}
					if(role.getLogin()!=null && role.getLogin().booleanValue()){
						memberRole.setLogin(new Boolean(true));
					}
					
					if(role.getVisituser()!=null && role.getVisituser().intValue()==1){
						memberRole.setVisituser(new Integer(1));
					}
//					发布的权限
					String chargeRes = role.getChargeRes();
					if(!StringUtils.isEmpty(chargeRes)){
						String[] charges = chargeRes.split(",");
						for (int j = 0; j < charges.length; j++) {
							chargeSet.add(charges[j]);
						}
					}
//					查看的权限
					String accessRes = role.getAccessRes();
					if(!StringUtils.isEmpty(accessRes)){
						String[] accesss = accessRes.split(",");
						for (int j = 0; j < accesss.length; j++) {
							accessSet.add(accesss[j]);
						}
					}
				}

			}
//			发布权限
			int chargeI = 0;
			String chargeStr = "";
			 for( Iterator   it = chargeSet.iterator();  it.hasNext(); ){             
		         if(chargeI != 0){
		        	 chargeStr+=',';
		         }
		         chargeStr+=it.next();
		         chargeI++;
		     }
			 memberRole.setChargeRes(chargeStr);
//			 查看权限
			 int accessI = 0;
			String accessStr = "";
			 for( Iterator   it = accessSet.iterator();  it.hasNext(); ){             
		         if(accessI != 0){
		        	 accessStr+=',';
		         }
		         accessStr+=it.next();
		         accessI++;
		     }
			 memberRole.setAccessRes(accessStr);
			
		}
		if(memberRole.getVisituser()==null){
			memberRole.setVisituser(new Integer(2));
		}
		return memberRole;
	}
	
	public Role getRoledById(String id){
		if(StringUtils.isEmpty(id))return null;
		Map map = new HashMap();
		map.put("id", id);
		List roleList = memberDao.getRole(map);
		if(roleList != null && roleList.size() > 0){ 
			Role role = (Role) roleList.get(0);
			if(role.getAuthed() != null && role.getAuthed().booleanValue()){
				return role;
			}else{
				if(!"0".equals(role.getParentId())){
					return getRoledById(role.getParentId());
				}
			}
			
		}
		return null;
	}
	
	public void updateRole(Role role)throws Exception{
		memberDao.updateRole(role);
	}
	public List getRole(){
		return memberDao.getRole(null);
	}
	public List getRoleTree(String parentId){
		Map map = new HashMap();
		map.put("parentId", parentId);
		List roleList = memberDao.getRole(map);
		if(roleList != null && roleList.size() > 0 ){ 
			for (int i = 0; i < roleList.size(); i++) {
				Role role = (Role) roleList.get(i);
				role.setRoleList(getRoleTree(role.getId()));
			}
		}
		return roleList;
	}
	public List getContacts(){
		return memberDao.getContacts(null);
	}
	
	public Contacts getContactById(String id){
		if(StringUtils.isEmpty(id)) return null;
		Map map = new HashMap();
		map.put("id", id);
		List list = memberDao.getContacts(map);
		if(list != null && list.size() > 0){
			return (Contacts) list.get(0);
		}
		return null;
	}
	
	public PageModel getMembers(int page){
        int pageSize = 13;
        Map map = new HashMap(); 
        int startId = (page-1) * pageSize + 1; 
        map.put("startId", new Integer(startId));
        map.put("endId", new Integer(startId+pageSize));
        List list = memberDao.getMemberList(map);
        PageModel pageModel = new PageModel();
        pageModel.setList(list);
        pageModel.setCurrentPage(page);
        pageModel.setPageSize(pageSize);
        
        int count = memberDao.getMemberListCount(map);
        pageModel.setTotalRecord(count);
        pageModel.setTotalPage((int)Math.ceil((double)count/pageSize));
        return pageModel;
	}
	
	public PageModel getMembers(String search,String searchRole,int page){
        int pageSize = 8;
        Map map = new HashMap(); 
        int startId = (page-1) * pageSize + 1; 
        map.put("startId", new Integer(startId));
        map.put("endId", new Integer(startId+pageSize));
        map.put("search", search);
        map.put("searchRole", searchRole);
        List list = memberDao.getMemberList(map); 
        if(list != null && list.size() > 0){
        	for (int i = 0; i < list.size(); i++) {
				Member member = (Member) list.get(i);
				member.setPathName(getPathName(member.getId()));
				/*Role role = getRoleById(member.getRoleId());
				if(role != null){
					String path = role.getPath();
					if(!StringUtils.isEmpty(path)){
						String[] paths = path.split(",");
						StringBuffer pathName = new StringBuffer();
						for (int j = 1; j < paths.length; j++) {
							if(j != 1){
								pathName.append(" | ");
							}
								pathName.append(Constants.roleMap.get(paths[j]));
						}
						member.setPathName(pathName.toString());
					}
				}*/
				
			}
        }
        
        PageModel pageModel = new PageModel();
        pageModel.setList(list); 
        pageModel.setCurrentPage(page);
        pageModel.setPageSize(pageSize);
        
        int count = memberDao.getMemberListCount(map);
        pageModel.setTotalRecord(count);
        pageModel.setTotalPage((int)Math.ceil((double)count/pageSize));
        return pageModel;
	}
	
	public void createRole(Role role)throws Exception{
		if(role == null){
			return ;
		}
		Integer id = idService.generateId(Constants.TABLE_ROLE);
		role.setId(String.valueOf(id)); 
		try{
			Role roleP = getRoleById(role.getParentId()); 
			role.setPath(roleP.getPath()+","+id);
			memberDao.insertRole(role);
		}catch(Exception e){
			e.printStackTrace();
			throw new Exception();
		}
		
	}
	
	public boolean updateMember(Member member){
		member.setModifyDate(new Date());
        try{
        	if(member!=null && !StringUtils.isEmpty(member.getSchoolCode())){
        		member.setId(member.getSchoolCode());
        	}
        	memberDao.updateMember(member); 
        	return true;
        }catch(Exception e){
        	e.printStackTrace();
        	return false;
        }
		
	}
	public boolean saveMember(Member member){
	    if(member == null) return false;
	    try{
	        if(StringUtils.isEmpty(member.getId())){
	            member.setId(member.getSchoolCode());
	            Date now = new Date();
	            member.setCreateDate(now);
	            member.setModifyDate(now);
	            Member exsit = getMemberById(member.getId());
	            if(exsit == null){
	            	memberDao.insertMember(member);
	            }
	            
	           
	        }else{
	            member.setModifyDate(new Date());
	            memberDao.updateMember(member);
	        }
	        
	        Map map = new HashMap();
            map.put("member", member.getId());
            map.put("role", member.getRoleId());
            memberDao.insertMemberRole(map);
	    }catch(Exception e){
	        e.printStackTrace();
	        return false;
	    }
	    return true;
	}
	
	
	
	public void insertMemberRole(String member,String role) throws Exception{
		Map map = new HashMap();
        map.put("member", member);
        map.put("role", role);
        memberDao.insertMemberRole(map);
	}
	
	public boolean deleteMember(String id){
	    if(StringUtils.isEmpty(id)) return false; 
	    try{
	        Map map = new HashMap();
	        map.put("id", id);
	        memberDao.deleteMember(map);
        }catch(Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
	}
	
	public boolean deleteRole(String id){
	    if(StringUtils.isEmpty(id)) return false; 
	    try{
	        Map map = new HashMap();
	        map.put("id", id);
	        memberDao.deleteRole(map);
        }catch(Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
	}
	
	public void deleteMemberRole(String member,String role)throws Exception{
		Map map = new HashMap();
		map.put("member", member);
		map.put("role", role);
		try{
			memberDao.deleteMemberRole(map);
		}catch(Exception e){
			throw new Exception();
		}
		
	}
	
	public static void main(String[] args){
		MemberService service = new MemberService();
		TransActionService ts = new TransActionService();
		try {
            ts.startTransaction();
            Member member = new Member();
            member.setCreateDate(new Date());
            member.setModifyDate(new Date());
            member.setMobile("13585848867");
            member.setPassword("96e79218965eb72c92a549dd5a330112");
            member.setRoleId("1");
            member.setSchoolCode("252");
            member.setUsername("应江林");
            member.setId("3");
            service.saveMember(member);
            ts.commitTransAction();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            try {
                ts.endTransAction();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
		
		
	}

}
